<template>
  <view class="account-header">
    <view>
      <view>
        <u-navbar bgColor=" #fff" :title="props.title" fixed height="120">
          <template #left>
            <u-icon name="arrow-left" size="40" @click="goBack"></u-icon>
          </template>
          <template #center>
            <view class="title">
              <span>{{ props.title }}</span>
            </view>
          </template>
          <template #right>
            <slot name="right"></slot>
          </template>
        </u-navbar>
      </view>

      <u-modal :show="modalShow" showCancelButton @close="modalShow = false" @cancel="modalShow = false"
        @confirm="confirmExit">
        <template #default>
          <slot name="modal"></slot>
        </template>
      </u-modal>
    </view>
  </view>
</template>

<script setup>
import { defineProps, ref } from 'vue'
import { onBackPress } from '@dcloudio/uni-app'

const modalShow = ref(false)
const props = defineProps({
  title: {
    type: String,
    default: "test"
  },
  needModal: {
    type: Boolean,
    default: false
  },
  // 跳转回页面的url，返回时会验证是否在历史记录中
  // 在的话返回到对应页面，不在历史记录中会直接跳转过去
  jumpTo: {
    type: String,
    default: ""
  },
  switchTo: {
    type: String,
    default: ""
  },
})

const pages = getCurrentPages()
const url = props.jumpTo || props.switchTo

let isFirstBack = true

onBackPress(options => {
  if (options.from !== "navigateBack" && isFirstBack) {
    // 返回验证
    isFirstBack = false

    for (let i = pages.length - 2; i >= 0; --i) {
      const lastPage = pages[i]
      const max = pages.length - 1

      if (url.includes(lastPage?.route)) {
        uni.navigateBack({ delta: max - i })
        return true
      }
    }

    if (props.jumpTo) {
      uni.navigateTo({ url: url.split(",")[0] })
    } else {
      uni.switchTab({ url: url.split(",")[0] })
    }
    return true
  }
})

// page's functions
function confirmExit () {
  const url = props.jumpTo || props.switchTo

  for (let i = pages.length - 2; i >= 0; --i) {
    const lastPage = pages[i]
    const max = pages.length - 1

    if (url.includes(lastPage?.route)) {
      return uni.navigateBack({ delta: max - i })
    }
  }

  if (props.jumpTo) {
    uni.navigateTo({ url: url.split(",")[0] })
  } else {
    uni.switchTab({ url: url.split(",")[0] })
  }
}

function goBack () {
  if (props.needModal) {
    modalShow.value = true
  } else {
    confirmExit()
  }
}
</script>

<style scoped lang="scss">
.title {
  font-size: 36rpx;
}
</style>